﻿using System;
using System.IO;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.OpenApi.Models;

namespace WebApi.Swagger
{
    public static class SwaggerServiceCollectionExtensions
    {
        public static IServiceCollection AddExtensionSwagger(this IServiceCollection services, IConfiguration configuration, bool isGateway = false)
        {
            bool isEnableSwagger = Convert.ToBoolean(configuration["Swagger:Enabled"] ?? "false");
            if (!isEnableSwagger)
            {
                return services;
            }

            // 封装集成注入Swagger实例
            services.AddSwaggerGen(s =>
            {
                s.SwaggerDoc(configuration["Swagger:DocName"], new OpenApiInfo
                {
                    Title = configuration["Swagger:Title"],
                    Version = configuration["Swagger:Version"],
                    Description = configuration["Swagger:Description"],
                    Contact = new OpenApiContact
                    {
                        Name = configuration["Swagger:Contact:Name"],
                        Email = configuration["Swagger:Contact:Email"]
                    }
                });

                // 添加Token参数
                bool isEnableAuth = Convert.ToBoolean(configuration["Swagger:Jwt"] ?? "false");
                if (isEnableAuth)
                {
                    s.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                    {
                        In = ParameterLocation.Header,
                        Description = "Please enter JWT with Bearer into field",
                        Name = "Authorization",
                        Type = SecuritySchemeType.ApiKey
                    });

                    s.AddSecurityRequirement(new OpenApiSecurityRequirement
                    {
                      {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference()
                            {
                               Id = "Bearer",
                               Type = ReferenceType.SecurityScheme
                            }
                        }, Array.Empty<string>()
                      }
                    });

                }

                if (!isGateway)
                {
                    var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                    var xmlPath = Path.Combine(basePath, configuration["Swagger:XmlFile"]);
                    if (File.Exists(xmlPath))
                    {
                        s.IncludeXmlComments(xmlPath);
                    }
                }
            });

            return services;
        }
      
    }
}
